#include "serverview.h"
#include "ui_serverview.h"

ServerView::ServerView(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ServerView)
{
    ui->setupUi(this);
    QScreen* screen = QGuiApplication::primaryScreen();
    ui->leftWidget->setMaximumWidth(screen->availableGeometry().width()/5);
    init();
}

void ServerView::init()
{
//    if(m_server == nullptr){
//        m_server =  QSharedPointer<QTcpServer>();
//    }
//    QString ip = ui->serverIPLine->text();
//    int port = ui->listenPortLine->text().toInt();
//    if(!m_server->listen(QHostAddress(ip),static_cast<uint16_t>(port))){
//       QMessageBox::warning(this,"listen","listen faild!");
//       return;
//    }else{
//        qDebug() << "listen successful!";
//    }
//    connect(m_server.get(),&QTcpServer::newConnection,this,&ServerView::onNewConnection);
    connect(ui->bindBtn,&QPushButton::clicked,this,&ServerView::onBindBtnClicked);
    connect(ui->sendDataBtn,&QPushButton::clicked,this,&ServerView::onSendBtnClicked);
}

ServerView::~ServerView()
{
    if(m_server!=nullptr){
        m_server->close();
    }
    delete ui;
}

void ServerView::onNewConnection()
{
    while(m_server->hasPendingConnections()){
        QTcpSocket* newSock = m_server->nextPendingConnection();
        m_sockList.append(newSock);
        quint16 port = newSock->peerPort();
        qDebug() << newSock->peerAddress().toString();
        qDebug() << port;
        connect(newSock,&QTcpSocket::readyRead,this,[this,newSock](){
            qDebug() << newSock->errorString();
            if(newSock==nullptr){
                QMessageBox::information(this,"read data","nullptr");
                return;
            }
            if(newSock->bytesAvailable()<=0){
                QMessageBox::information(this,"read data","nothing to read");
                return;
            }
            QByteArray byteArr = newSock->readAll();
            QString str = QString(byteArr);
            ui->recvTextPlain->appendPlainText(str);
        });
        connect(newSock,&QTcpSocket::disconnected,this,[this,newSock](){
            this->m_sockList.removeOne(newSock);
            newSock->deleteLater();
            QMessageBox::warning(this,"connect","disconnect!");
        });
    }
}

void ServerView::onSendBtnClicked()
{
    QString str{""};
    QTextDocument* doc = ui->sendTextPlain->document();
    for (auto it=doc->begin();it!=doc->end();it=it.next()) {
        str+=it.text();
    }
    qDebug() << str;
    for(auto sock:m_sockList){
        sock->write(str.toStdString().c_str());
    }
}

void ServerView::onBindBtnClicked()
{
    if(m_server == nullptr){
        m_server =  QSharedPointer<QTcpServer>(new QTcpServer);
    }
    // 如果已经绑定过，则close后，在绑定新的端口
    if(m_server->isListening()){
        m_server->close();
        disconnect(m_server.get(),&QTcpServer::newConnection,this,&ServerView::onNewConnection);
    }
    QString ip = ui->serverIPLine->text();
    int port = ui->listenPortLine->text().toInt();
    qDebug() << ip<<":"<<QString(port);
    if(!m_server->listen(QHostAddress(ip),static_cast<uint16_t>(port))){
       QMessageBox::warning(this,"listen","listen faild!");
       return;
    }else{
        QMessageBox::information(this,"listen","listen port:" +QString::asprintf("%1").arg(port)+ " successful!");
    }
    connect(m_server.get(),&QTcpServer::newConnection,this,&ServerView::onNewConnection);
}
